package com.ibiaoke.system.dao;

import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;

public class NetTest {
	private static Integer cur = 1;
	private static int count=0;
	
	static class Scope{
		private int start;
		private int end;
		public int getStart() {
			return start;
		}
		public void setStart(int start) {
			this.start = start;
		}
		public int getEnd() {
			return end;
		}
		public void setEnd(int end) {
			this.end = end;
		}
		
		
	}
	public synchronized static Scope getTask(){
		if(cur >= 255){
			return null;
		}
		Scope s= new Scope();
		s.setStart(cur);
		s.setEnd((cur + 9) >= 255? 254:(cur + 9));
		cur += 10;
		return s;
	}
	
	public synchronized static void addOnlineCount(){
		count++;
	}

	public static void main(String[] args) throws UnknownHostException, IOException {

		System.out.println("开启局域网内在线电脑扫描...");
		List<Thread> ts = new ArrayList<Thread>();

		for (int i = 0; i < 26; i++) {
			Thread t= new Thread(new Runnable() {
				@Override
                public void run() {
					Scope curTask = NetTest.getTask();
					if(curTask != null){
						for(int i= curTask.getStart();i <=curTask.getEnd();i++){
							String host = "192.168.2." + i;
							int timeOut = 3000; // 超时应该在3钞以上
							boolean status =false;
							try {
								status = InetAddress.getByName(host).isReachable(timeOut);
							} catch (UnknownHostException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							} catch (IOException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
							if(status){
								addOnlineCount();
								System.out.println(host);
							}
							
						}
					}
				}
			});
			t.start();
			ts.add(t);
		}
		
		for(Thread t:ts){
			try {
				t.join();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		System.out.println("192.168.2.x网段内，总共" + count + "个电脑在线");
	}
}
